import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:qyou_app/model/result.dart';

/*
 * http请求工具
 */
class HttpKit {
  // 单例模式
  static final HttpKit _instance = HttpKit._internal();
  factory HttpKit() => _instance;
  Dio _dio;

  HttpKit._internal() {
    init();
  }

  // 初始化请求配置
  init() {
    BaseOptions baseOptions = BaseOptions(
      //baseUrl: "https://1af95c77-1b43-4d9b-b253-b8aad3e529f3.mock.pstmn.io",
      baseUrl: "http://192.168.1.21:8080",
      //baseUrl: "http://192.168.0.107:8080",
      responseType: ResponseType.json,
      connectTimeout: 5000,
      receiveTimeout: 3000,
    );
    _dio = Dio(baseOptions);
  }

  // 请求(默认post)
  Future request(String url,
      {String method = "post", Map<String, dynamic> params}) async {
    Options options = Options(method: method);
    try {
      final result =
          await _dio.request(url, queryParameters: params, options: options);
      return result;
    } on DioError catch (error) {
      throw error;
    }
  }

  Future get(String url,
      {String method = "get", Map<String, dynamic> params}) async {
    Options options = Options(method: method);
    try {
      print("url：$url");
      final result =
      await _dio.request(url, queryParameters: params, options: options);
      Map map = json.decode(result.toString());
      return Result.fromJson(map);
    } on DioError catch (error) {
      throw error;
    }
  }

  Future post(String url,
      {String method = "post", Map<String, dynamic> params}) async {
    Options options = Options(method: method);
    try {
      final result =
      await _dio.request(url, queryParameters: params, options: options);
      return result;
    } on DioError catch (error) {
      throw error;
    }
  }
}